package com.content.scaffold.common.advice;

import com.content.scaffold.common.exception.BaseException;
import com.content.scaffold.common.exception.DataModifyException;
import com.content.scaffold.common.exception.UnauthorizedException;
import com.content.scaffold.common.web.ResponseCodeEnum;
import com.content.scaffold.common.web.ResultBody;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author xiaojl
 */
@Slf4j
@RestControllerAdvice
public class ControllerHandlers {

    /**
     * 兜底异常
     */
    @ExceptionHandler(Exception.class)
    public ResultBody<Void> errorHandler(Exception e, HttpServletResponse response) {
        response.setStatus(HttpStatus.OK.value());
        log.error("服务未知异常", e);
        return ResultBody.error();
    }

    @ExceptionHandler(DataModifyException.class)
    public ResultBody<Void> dataModifyHandler(DataModifyException e, HttpServletResponse response) {
        log.error("数据读写异常", e);
        response.setStatus(HttpStatus.OK.value());
        return new ResultBody<Void>().code(e.getCode()).msg(e.getMessage());
    }

    @ExceptionHandler(BaseException.class)
    public ResultBody<Void> baseHandler(BaseException e, HttpServletResponse response) {
        log.error("业务异常", e);
        response.setStatus(HttpStatus.OK.value());
        return new ResultBody<Void>().code(e.getCode()).msg(e.getMessage());
    }

    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public ResultBody<Void> requestMethodNotSupportedHandler(HttpRequestMethodNotSupportedException e, HttpServletResponse response) {
        String method = e.getMethod();
        log.error("请求不支持异常，请求方法: {}", method, e);
        response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
        return new ResultBody<Void>().code(ResponseCodeEnum.ERROR.getCode()).msg("请求方式有问题，请确认！");
    }

    @ExceptionHandler(UnauthorizedException.class)
    public ResultBody<Void> unauthorizedHandler(UnauthorizedException e, HttpServletResponse response) {
        log.error("用户未登录", e);
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        return new ResultBody<Void>().code(e.getCode()).msg(e.getMessage());
    }

    /**
     * 处理 @RequestBody 参数验证失败的异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResultBody<Void> exceptionHandler(MethodArgumentNotValidException exception, HttpServletResponse response) {
        response.setStatus(HttpStatus.OK.value());
        BindingResult result = exception.getBindingResult();
        List<String> errorMessages = result.getAllErrors()
                .stream()
                .map(ObjectError::getDefaultMessage)
                .collect(Collectors.toList());
        return ResultBody.error(String.join(", ", errorMessages));
    }

    /**
     * 处理 @RequestParam 或 @PathVariable 参数验证失败的异常
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public ResultBody<Void> exceptionHandler(ConstraintViolationException ex) {
        String message = ex.getConstraintViolations()
                .stream()
                .map(ConstraintViolation::getMessage)
                .collect(Collectors.joining(", "));
        return ResultBody.error(message);
    }
}
